import React, { PureComponent } from 'react';
import { connect } from 'dva';
import { Form } from '@ant-design/compatible';
import '@ant-design/compatible/assets/index.css';
import { message } from 'antd';
import moment from 'moment';
import { ContentPackage, TableC, DATA_ENTRY, AdvancedSearch, PrimaryC, NoQueryC } from '../../../comps';
import styles from './index.less';
import SceneModal from './sceneModal';
import { fixedNum } from '../../../utils/utils';

@Form.create()
class PressureTest extends PureComponent {
  state = {
    dictionary: {}, //所有字典枚举
    sceneNameList: [], //情景名称列表
    columns: [],
    dataSource: [],
    pageInfo: {},
    search: false, //是否有搜索条件---fales-显示无查询模块
    productId: [], //产品id
    productGroupId: '', //产品组id
    sceneId: '', //情景名称id
    time: '', //分析日期
    tradingDate: '', //分析日期--默认前一交易日
    visibleModal: false, //情景设置弹窗
  };

  componentDidMount() {
    this.getSceneNameList();
    const {
      globalM: {
        dataDictionary: { OTC_OPTION_BOOK_OPTIONTYPE = [] },
      },
    } = this.props;
    this.setState({
      dictionary: { OTC_OPTION_BOOK_OPTIONTYPE },
    });
    this.props.dispatch({
      type: 'pressureTestM/getTradingDate',
      payload: { type: '1' },
      callback: (res) => {
        this.setState({
          tradingDate: res,
        });
      },
    });
  }

  //获取情景名称列表
  getSceneNameList = () => {
    const { dispatch } = this.props;
    dispatch({
      type: 'pressureTestM/getSceneNameList',
      payload: '',
      callback: (res) => {
        const newData = res.dataSource.filter((item) => item.sceneId == this.state.sceneId);
        if (newData.length == 0 && this.state.sceneId) {
          //当前搜索条件情景名称被删除
          this.sceneIdSet.props.form.setFieldsValue({
            sceneId: undefined,
          });
          this.setState({
            sceneId: '',
            search: false,
          });
        }
        this.setState({
          sceneNameList: res.dataSource,
        });
      },
    });
  };

  //获取table列表
  getTableData = () => {
    const { dispatch } = this.props;
    const { productId, productGroupId, sceneId, time } = this.state;

    dispatch({
      type: 'pressureTestM/getTableData',
      payload: {
        productId: productId.length ? productId : null,
        productGroupId: productGroupId ? productGroupId : null,
        sceneId: sceneId,
        time: time.format('YYYY-MM-DD'),
        currentPage: 1,
        numInPage: 20,
      },
      callback: (res) => {
        this.setState({
          columns: res.columns,
          dataSource: res.dataSource,
          pageInfo: res.pageInfo,
        });
      },
    });
  };

  //产品组select变化
  portfolioCodeChange = (e) => {
    //选择产品组清空产品
    this.product.props.form.setFieldsValue({
      productList: undefined,
    });
    this.setState({
      productGroupId: e ? e.key : '',
      productId: [],
    });
  };

  //产品select变化
  productListChange = (e) => {
    //选择产品清空产品组
    this.productGroup.props.form.setFieldsValue({
      portfolioCodeList: undefined,
    });
    this.setState({
      productId: e ? e.key : [],
      productGroupId: '',
    });
  };

  //情景名称select变化
  sceneIdChange = (e) => {
    this.setState({
      sceneId: e ? e : '',
    });
  };

  // 优化columns的渲染
  changeColumns = (columns) => {
    const {
      dictionary: { OTC_OPTION_BOOK_OPTIONTYPE = [] },
    } = this.state;
    let newColumns = columns;
    if (newColumns && newColumns.length) {
      newColumns.map((item) => {
        if (item.key == 'firstKnockoutDate' || item.key == 'firstKnockinDate' || item.key == 'sceneLossDate') {
          item.render = (val) => <span>{val ? moment(val).format('YYYY-MM-DD') : '--'}</span>;
        }
        if (item.key == 'optionType') {
          item.render = (text, row) => OTC_OPTION_BOOK_OPTIONTYPE.filter((x) => x.code == text)[0]?.value || '--';
        }
        if (item.key == 'sceneLoss') {
          item.render = (text, record) => {
            return text ? fixedNum(text * 1) : text == 0 ? text : '--';
          };
        }
      });
    }
    return newColumns;
  };

  //打开详情弹窗
  openModal = () => {
    this.setState({
      visibleModal: !this.state.visibleModal,
    });
  };

  //改变情景名称列表数据格式
  changeSceneListData = (arr) => {
    const list = [];
    arr.map((item) => {
      let obj = {
        title: item.sceneName,
        value: item.sceneId,
      };
      list.push(obj);
    });
    return list;
  };

  //表格change事件
  onTableChange = (current, size) => {
    const { dispatch } = this.props;
    const { productId, productGroupId, sceneId, time } = this.state;

    dispatch({
      type: 'pressureTestM/getTableData',
      payload: {
        productId: productId.length ? productId : null,
        productGroupId: productGroupId ? productGroupId : null,
        sceneId: sceneId,
        time: time.format('YYYY-MM-DD'),
        currentPage: current,
        numInPage: size,
      },
      callback: (res) => {
        this.setState({
          columns: res.columns,
          dataSource: res.dataSource,
          pageInfo: res.pageInfo,
        });
      },
    });
  };

  render() {
    const { sceneNameList, columns, dataSource, pageInfo, productGroupId, productId, tradingDate, visibleModal, search } = this.state;
    const { form, loading } = this.props;
    const newColumns = this.changeColumns(columns);
    const newsceneNameList = this.changeSceneListData(sceneNameList);
    const searchProps = {
      dataSource: [
        {
          dataIndex: 'portfolioCodeList',
          title: '产品组',
          type: DATA_ENTRY.PRODUCTGROUP,
          multiple: false,
          onRef: (ref) => (this.productGroup = ref),
          onChange: this.portfolioCodeChange,
          tradeModel: ['BOOKKEEPING_MODE', 'COMMAND_MODE'], //只有簿记和指令模式产品
        },
        {
          dataIndex: 'productList',
          title: '产品',
          type: DATA_ENTRY.PRODUCTLIST,
          dataType: 2,
          multiple: true,
          onRef: (ref) => (this.product = ref),
          onChange: this.productListChange,
          tradeModel: ['BOOKKEEPING_MODE', 'COMMAND_MODE'], //只有簿记和指令模式产品
        },
        {
          dataIndex: 'sceneId',
          title: '情景名称',
          type: DATA_ENTRY.SELECT,
          dataSource: newsceneNameList,
          allowClear: true,
          onRef: (ref) => (this.sceneIdSet = ref),
          onChange: this.sceneIdChange,
          filterOption: (input, option) => option.props.children.toLowerCase().indexOf(input.toLowerCase()) >= 0,
        },
        {
          dataIndex: 'time',
          title: '分析日期',
          type: DATA_ENTRY.SINGLEDATE,
          initialValue: moment(tradingDate),
          disableEnd: moment(),
          rules: [{ required: false, message: '请选择分析日期!' }],
        },
      ],
      onQuery: (e) => {
        if (!e.portfolioCodeList && !(e.productList && e.productList.length > 0)) {
          message.warning('请选择产品组或产品');
          return;
        }
        if (!e.sceneId) {
          message.warning('请选择情景名称');
          return;
        }
        if (!e.time) {
          message.warning('请选择分析日期');
          return;
        }
        this.setState(
          {
            search: true,
            time: e.time,
          },
          () => {
            this.getTableData();
          },
        );
      },
      onClear: () => {
        form.resetFields();
        this.setState({
          productId: [],
          productGroupId: '',
          sceneId: '',
          time: '',
        });
      },
    };

    return (
      <ContentPackage
        title='场外期权压力测试'
        contentHtml={
          <div className={styles.pressureTest}>
            <div>
              <AdvancedSearch {...searchProps} />
            </div>
            <PrimaryC
              title='情景设置'
              style={{ margin: '10px 0' }}
              onClick={() => {
                this.openModal();
              }}
            />
            {search ? (
              <TableC
                columns={newColumns}
                dataSource={dataSource}
                loading={loading.effects['pressureTestM/getTableData'] === true}
                current={pageInfo && pageInfo.currentPage}
                total={pageInfo && pageInfo.total}
                pageSize={pageInfo && pageInfo.numInPage}
                onShowSizeChange={(current, size) => this.onTableChange(current, size)}
                onPageChange={(page, pageSize) => this.onTableChange(page, pageSize)}
                selfScrollY={true}
                rowKey='id'
              />
            ) : (
              <NoQueryC />
            )}
            <SceneModal sceneNameList={sceneNameList} visibleModal={visibleModal} openModal={this.openModal} getSceneNameList={this.getSceneNameList} />
          </div>
        }
      />
    );
  }
}
export default connect(({ pressureTestM, loading, globalM }) => ({ pressureTestM, loading, globalM }))(PressureTest);
